const Recipe = require('../models/Recipe');
const mongoose = require('mongoose');

/**
 * 获取推荐食谱列表
 * @route GET /api/diet/recipes/featured
 * @param {number} limit - 获取数量限制，默认为4
 * @returns {Array} 推荐食谱列表
 */
exports.getFeaturedRecipes = async (req, res) => {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit) : 4;
    
    const recipes = await Recipe.find({ featured: true })
      .select('name description calories carbs protein fat imageUrl cookingTime difficulty isNutritionCalculated')
      .limit(limit);
    
    res.json({
      success: true,
      data: recipes
    });
  } catch (error) {
    console.error('获取推荐食谱失败:', error);
    res.status(500).json({
      success: false,
      message: '获取推荐食谱失败',
      error: error.message
    });
  }
};

/**
 * 获取食谱详情
 * @route GET /api/diet/recipes/:id
 * @param {string} id - 食谱ID
 * @returns {Object} 食谱详情
 */
exports.getRecipeById = async (req, res) => {
  try {
    const recipe = await Recipe.findById(req.params.id)
      .populate('ingredients.food', 'name category calories carbs protein fat fiber sugar');
    
    if (!recipe) {
      return res.status(404).json({
        success: false,
        message: '食谱未找到'
      });
    }
    
    res.json({
      success: true,
      data: recipe
    });
  } catch (error) {
    console.error('获取食谱详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取食谱详情失败',
      error: error.message
    });
  }
};

/**
 * 搜索食谱
 * @route GET /api/diet/recipes/search
 * @param {string} query - 搜索关键词
 * @param {string} tags - 标签，逗号分隔
 * @param {string} difficulty - 难度级别
 * @returns {Array} 符合条件的食谱列表
 */
exports.searchRecipes = async (req, res) => {
  try {
    const { query, tags, difficulty } = req.query;
    const searchQuery = {};
    
    // 添加文本搜索条件
    if (query) {
      searchQuery.$text = { $search: query };
    }
    
    // 按标签筛选
    if (tags) {
      const tagArray = tags.split(',');
      searchQuery.tags = { $in: tagArray };
    }
    
    // 按难度筛选
    if (difficulty) {
      searchQuery.difficulty = difficulty;
    }
    
    const recipes = await Recipe.find(searchQuery)
      .select('name description calories carbs protein fat imageUrl cookingTime difficulty');
    
    res.json({
      success: true,
      count: recipes.length,
      data: recipes
    });
  } catch (error) {
    console.error('搜索食谱失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索食谱失败',
      error: error.message
    });
  }
};

/**
 * 获取适合特定健康状况的食谱
 * @route GET /api/diet/recipes/suitable
 * @param {string} condition - 健康状况，如"糖尿病"
 * @param {string} stage - 阶段，如"轻度"
 * @returns {Array} 符合条件的食谱列表
 */
exports.getRecipesBySuitability = async (req, res) => {
  try {
    const { condition, stage } = req.query;
    const searchQuery = {};
    
    if (condition) {
      searchQuery['suitableFor.condition'] = condition;
      
      if (stage) {
        searchQuery['suitableFor.stage'] = stage;
      }
    }
    
    const recipes = await Recipe.find(searchQuery)
      .select('name description calories carbs protein fat imageUrl cookingTime difficulty suitableFor');
    
    res.json({
      success: true,
      count: recipes.length,
      data: recipes
    });
  } catch (error) {
    console.error('获取适合特定健康状况的食谱失败:', error);
    res.status(500).json({
      success: false,
      message: '获取适合特定健康状况的食谱失败',
      error: error.message
    });
  }
};

/**
 * 初始化食谱数据（首次启动时调用）
 * 仅当数据库中没有食谱数据时添加初始数据
 */
exports.initializeRecipes = async () => {
  try {
    // 检查数据库是否已有食谱数据
    const count = await Recipe.countDocuments();
    if (count > 0) {
      console.log('食谱数据库已初始化，包含 ' + count + ' 条记录');
      return;
    }
    
    console.log('食谱数据库为空，准备初始化');
    
    // 先获取常用食物数据
    const Food = require('../models/Food');
    
    // 查找常用食材
    let rice = await Food.findOne({ name: '米饭' });
    let egg = await Food.findOne({ name: '鸡蛋' });
    let chicken = await Food.findOne({ name: /鸡胸肉|鸡肉/ });
    let broccoli = await Food.findOne({ name: /花椰菜|西兰花/ });
    let oats = await Food.findOne({ name: /燕麦|麦片/ });
    let quinoa = await Food.findOne({ name: /藜麦/ });
    let milk = await Food.findOne({ name: /牛奶/ });
    let carrot = await Food.findOne({ name: /胡萝卜/ });
    let spinach = await Food.findOne({ name: /菠菜/ });
    let tomato = await Food.findOne({ name: /西红柿|番茄/ });
    let tofu = await Food.findOne({ name: /豆腐/ });
    let soymilk = await Food.findOne({ name: /豆浆/ });
    let beef = await Food.findOne({ name: /牛肉/ });
    let yogurt = await Food.findOne({ name: /酸奶|酵母乳/ });
    let strawberry = await Food.findOne({ name: /草莓/ });
    let blueberry = await Food.findOne({ name: /蓝莓/ });
    let fish = await Food.findOne({ name: /鱼|鲈鱼/ });
    let asparagus = await Food.findOne({ name: /芦笋/ });
    
    // 如果找不到某些食材，创建默认值
    const createDefaultFood = (name, category, nutrition) => {
      return {
        _id: new mongoose.Types.ObjectId(),
        name,
        category,
        ...nutrition
      };
    };
    
    // 创建默认食材，如果在数据库中未找到
    if (!rice) rice = createDefaultFood('米饭', '主食', { calories: 116, carbs: 25.8, protein: 2.6, fat: 0.3, fiber: 0.4, sugar: 0.1 });
    if (!egg) egg = createDefaultFood('鸡蛋', '蛋类', { calories: 155, carbs: 1.1, protein: 12.8, fat: 10.8, fiber: 0, sugar: 0.7 });
    if (!chicken) chicken = createDefaultFood('鸡胸肉', '肉类', { calories: 165, carbs: 0, protein: 31, fat: 3.6, fiber: 0, sugar: 0 });
    if (!broccoli) broccoli = createDefaultFood('花椰菜', '蔬菜', { calories: 34, carbs: 6.6, protein: 2.8, fat: 0.4, fiber: 2.6, sugar: 1.7 });
    if (!oats) oats = createDefaultFood('燕麦片', '谷物', { calories: 389, carbs: 66.3, protein: 16.9, fat: 6.9, fiber: 10.6, sugar: 0.8 });
    if (!quinoa) quinoa = createDefaultFood('藜麦', '谷物', { calories: 368, carbs: 64.2, protein: 14.1, fat: 6.1, fiber: 7, sugar: 0 });
    if (!milk) milk = createDefaultFood('牛奶', '乳制品', { calories: 42, carbs: 5, protein: 3.4, fat: 1, fiber: 0, sugar: 5 });
    if (!carrot) carrot = createDefaultFood('胡萝卜', '蔬菜', { calories: 41, carbs: 9.6, protein: 0.9, fat: 0.2, fiber: 2.8, sugar: 4.7 });
    if (!spinach) spinach = createDefaultFood('菠菜', '蔬菜', { calories: 23, carbs: 3.6, protein: 2.9, fat: 0.4, fiber: 2.2, sugar: 0.4 });
    if (!tomato) tomato = createDefaultFood('西红柿', '蔬菜', { calories: 18, carbs: 3.9, protein: 0.9, fat: 0.2, fiber: 1.2, sugar: 2.6 });
    if (!tofu) tofu = createDefaultFood('豆腐', '豆制品', { calories: 83, carbs: 4.2, protein: 9.3, fat: 4.8, fiber: 0.3, sugar: 0.7 });
    if (!soymilk) soymilk = createDefaultFood('豆浆', '饮品', { calories: 33, carbs: 2.8, protein: 3.3, fat: 1.6, fiber: 0.3, sugar: 0 });
    if (!beef) beef = createDefaultFood('瘦牛肉', '肉类', { calories: 250, carbs: 0, protein: 26, fat: 15, fiber: 0, sugar: 0 });
    if (!yogurt) yogurt = createDefaultFood('希腊酸奶', '乳制品', { calories: 59, carbs: 3.6, protein: 10, fat: 0.4, fiber: 0, sugar: 3.6 });
    if (!strawberry) strawberry = createDefaultFood('草莓', '水果', { calories: 32, carbs: 7.7, protein: 0.7, fat: 0.3, fiber: 2, sugar: 4.9 });
    if (!blueberry) blueberry = createDefaultFood('蓝莓', '水果', { calories: 57, carbs: 14.5, protein: 0.7, fat: 0.3, fiber: 2.4, sugar: 10 });
    if (!fish) fish = createDefaultFood('鲈鱼', '海鲜', { calories: 97, carbs: 0, protein: 19.4, fat: 1.7, fiber: 0, sugar: 0 });
    if (!asparagus) asparagus = createDefaultFood('芦笋', '蔬菜', { calories: 20, carbs: 3.9, protein: 2.2, fat: 0.2, fiber: 2.1, sugar: 1.3 });
    
    // 初始化食谱数据
    const initialRecipes = [
      // 早餐食谱
      {
        name: '燕麦藜麦碗',
        description: '富含膳食纤维的早餐，有助于稳定血糖',
        mealType: ['breakfast'],
        category: ['grain', 'fruit'],
        // 营养数据会根据配料自动计算
        servingSize: 1,
        cookingTime: 15,
        difficulty: '简单',
        imageUrl: '/images/recipes/oatmeal-quinoa.jpg',
        ingredients: [
          { 
            food: oats._id, 
            foodName: oats.name, 
            amount: '40g', 
            gramWeight: 40 
          },
          { 
            food: quinoa._id, 
            foodName: quinoa.name, 
            amount: '20g', 
            gramWeight: 20 
          },
          { 
            food: milk._id, 
            foodName: milk.name, 
            amount: '100ml', 
            gramWeight: 100 
          },
          { 
            food: blueberry._id, 
            foodName: blueberry.name, 
            amount: '30g', 
            gramWeight: 30 
          }
        ],
        steps: [
          { order: 1, description: '藜麦洗净，放入小锅中加水煮10分钟至熟软' },
          { order: 2, description: '另起一锅，将燕麦片和牛奶、水一起煮5分钟' },
          { order: 3, description: '将煮好的藜麦和燕麦混合' },
          { order: 4, description: '加入蓝莓、杏仁和肉桂粉混合即可' }
        ],
        tags: ['早餐', '高纤维', '糖尿病友好', '素食'],
        suitableFor: [
          { condition: '糖尿病', stage: '全阶段' },
          { condition: '高血脂', stage: '轻度' }
        ],
        featured: true
      },
      
      // 蔬菜煎蛋
      {
        name: '蔬菜煎蛋',
        description: '低碳水高蛋白的健康早餐选择',
        mealType: ['breakfast'],
        category: ['vegetable', 'chicken'],
        servingSize: 1,
        cookingTime: 10,
        difficulty: '简单',
        imageUrl: '/images/recipes/vegetable-omelette.jpg',
        ingredients: [
          { 
            food: egg._id, 
            foodName: egg.name, 
            amount: '2个', 
            gramWeight: 100 
          },
          { 
            food: spinach._id, 
            foodName: spinach.name, 
            amount: '30g', 
            gramWeight: 30 
          },
          { 
            food: tomato._id, 
            foodName: tomato.name, 
            amount: '半个', 
            gramWeight: 50 
          }
        ],
        steps: [
          { order: 1, description: '洋葱切丁，西红柿切丁，菠菜洗净切碎' },
          { order: 2, description: '鸡蛋打散，加入盐和黑胡椒调味' },
          { order: 3, description: '平底锅中加入橄榄油，炒香洋葱' },
          { order: 4, description: '加入西红柿和菠菜翻炒30秒' },
          { order: 5, description: '倒入蛋液，小火煎至凝固即可' }
        ],
        tags: ['早餐', '高蛋白', '低碳水', '糖尿病友好'],
        suitableFor: [
          { condition: '糖尿病', stage: '全阶段' },
          { condition: '高血压', stage: '轻度' }
        ],
        featured: false
      },
      
      // 豆浆豆腐脑
      {
        name: '豆浆豆腐脑',
        description: '传统健康早餐，富含优质植物蛋白',
        mealType: ['breakfast'],
        category: ['bean'],
        servingSize: 1,
        cookingTime: 5,
        difficulty: '简单',
        imageUrl: '/images/recipes/tofu-pudding.jpg',
        ingredients: [
          { 
            food: tofu._id, 
            foodName: tofu.name, 
            amount: '200g', 
            gramWeight: 200 
          },
          { 
            food: soymilk._id, 
            foodName: soymilk.name, 
            amount: '200ml', 
            gramWeight: 200 
          }
        ],
        steps: [
          { order: 1, description: '将豆腐脑放入碗中' },
          { order: 2, description: '撒上葱花和香菜' },
          { order: 3, description: '淋上芝麻油和酱油' },
          { order: 4, description: '配上豆浆一起食用' }
        ],
        tags: ['早餐', '高蛋白', '素食', '糖尿病友好'],
        suitableFor: [
          { condition: '糖尿病', stage: '全阶段' },
          { condition: '高血脂', stage: '轻度' }
        ],
        featured: false
      },
      
      // 蒸鸡胸肉配花椰菜
      {
        name: '蒸鸡胸肉配花椰菜',
        description: '低热量高蛋白的健康餐，适合糖尿病患者',
        mealType: ['lunch', 'dinner'],
        category: ['chicken', 'vegetable'],
        servingSize: 1,
        cookingTime: 25,
        difficulty: '简单',
        imageUrl: '/images/recipes/steamed-chicken.jpg',
        ingredients: [
          { 
            food: chicken._id, 
            foodName: chicken.name, 
            amount: '150g', 
            gramWeight: 150 
          },
          { 
            food: broccoli._id, 
            foodName: broccoli.name, 
            amount: '100g', 
            gramWeight: 100 
          }
        ],
        steps: [
          { order: 1, description: '鸡胸肉洗净，切成厚片' },
          { order: 2, description: '花椰菜洗净，切成小朵' },
          { order: 3, description: '将鸡胸肉和花椰菜放入蒸锅，撒上盐和黑胡椒' },
          { order: 4, description: '大火蒸15分钟' },
          { order: 5, description: '取出后淋上橄榄油即可食用' }
        ],
        tags: ['高蛋白', '低碳水', '糖尿病友好'],
        suitableFor: [
          { condition: '糖尿病', stage: '全阶段' },
          { condition: '高血压', stage: '轻度' }
        ],
        featured: true
      },
      
      // 糙米蔬菜饭
      {
        name: '糙米蔬菜饭',
        description: '低GI值的主食，富含膳食纤维',
        mealType: ['lunch', 'dinner'],
        category: ['grain', 'vegetable'],
        servingSize: 1,
        cookingTime: 40,
        difficulty: '中等',
        imageUrl: '/images/recipes/brown-rice.jpg',
        ingredients: [
          { 
            food: rice._id, 
            foodName: rice.name, 
            amount: '100g', 
            gramWeight: 100 
          },
          { 
            food: carrot._id, 
            foodName: carrot.name, 
            amount: '30g', 
            gramWeight: 30 
          }
        ],
        steps: [
          { order: 1, description: '糙米洗净，浸泡30分钟' },
          { order: 2, description: '胡萝卜切丁，洋葱切碎' },
          { order: 3, description: '锅中加入橄榄油，炒香洋葱' },
          { order: 4, description: '加入胡萝卜、青豆、玉米粒炒1分钟' },
          { order: 5, description: '加入糙米和适量水，大火煮开后转小火煮30分钟' },
          { order: 6, description: '加入少许盐调味即可' }
        ],
        tags: ['主食', '高纤维', '低GI', '素食'],
        suitableFor: [
          { condition: '糖尿病', stage: '全阶段' },
          { condition: '高血脂', stage: '轻度' }
        ],
        featured: true
      },
      
      // 清蒸鱼配芦笋
      {
        name: '清蒸鱼配芦笋',
        description: '富含优质蛋白和ω-3脂肪酸的健康餐',
        mealType: ['lunch', 'dinner'],
        category: ['seafood', 'vegetable'],
        servingSize: 1,
        cookingTime: 20,
        difficulty: '中等',
        imageUrl: '/images/recipes/steamed-fish.jpg',
        ingredients: [
          { 
            food: fish._id, 
            foodName: fish.name, 
            amount: '200g', 
            gramWeight: 200 
          },
          { 
            food: asparagus._id, 
            foodName: asparagus.name, 
            amount: '100g', 
            gramWeight: 100 
          }
        ],
        steps: [
          { order: 1, description: '鱼洗净，两面划几刀' },
          { order: 2, description: '姜切丝，葱切段' },
          { order: 3, description: '芦笋洗净，切去老根' },
          { order: 4, description: '将姜丝铺在盘底，放上鱼' },
          { order: 5, description: '大火蒸8-10分钟' },
          { order: 6, description: '同时将芦笋放入沸水中焯1分钟' },
          { order: 7, description: '取出鱼，撒上葱段，淋上蒸鱼豉油和热橄榄油' },
          { order: 8, description: '将芦笋摆盘，与鱼一起食用' }
        ],
        tags: ['高蛋白', '低碳水', '海鲜'],
        suitableFor: [
          { condition: '糖尿病', stage: '全阶段' },
          { condition: '高血压', stage: '轻度' }
        ],
        featured: true
      }
    ];
    
    // 创建包含食物引用的食谱
    for (const recipeData of initialRecipes) {
      const recipe = new Recipe(recipeData);
      
      // 尝试计算营养成分
      try {
        await recipe.calculateNutrition();
        console.log(`成功计算食谱 "${recipe.name}" 的营养成分`);
      } catch (error) {
        console.error(`无法计算食谱 "${recipe.name}" 的营养成分:`, error);
        // 如果计算失败，使用默认值
        // 这些值未来可根据实际情况优化
        recipe.calories = 200 + Math.floor(Math.random() * 300);
        recipe.carbs = 10 + Math.floor(Math.random() * 40);
        recipe.protein = 10 + Math.floor(Math.random() * 25);
        recipe.fat = 5 + Math.floor(Math.random() * 15);
        recipe.fiber = 2 + Math.floor(Math.random() * 6);
        recipe.sugar = 1 + Math.floor(Math.random() * 8);
      }
      
      await recipe.save();
    }
    
    console.log('成功初始化食谱数据库，添加了 ' + initialRecipes.length + ' 条食谱记录');
  } catch (error) {
    console.error('初始化食谱数据库失败:', error);
  }
};

/**
 * 获取食谱列表（支持分类筛选和分页）
 * @route GET /api/diet/recipes
 * @param {string} mealType - 主分类（早餐/午餐/晚餐）
 * @param {string} category - 子分类（鸡肉类/豆制品类等）
 * @param {number} page - 页码，默认为1
 * @param {number} limit - 每页数量，默认为10
 * @returns {Array} 食谱列表
 */
exports.getRecipes = async (req, res) => {
  try {
    const { mealType, category, limit = 10, page = 1 } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    // 构建查询条件
    const query = {};
    
    if (mealType && mealType !== 'all') {
      query.mealType = mealType;
    }
    
    if (category && category !== 'all') {
      query.category = category;
    }
    
    // 执行查询
    const recipes = await Recipe.find(query)
      .sort({ featured: -1, updatedAt: -1 })
      .skip(skip)
      .limit(parseInt(limit))
      .select('name description calories carbs protein fat imageUrl cookingTime difficulty mealType category');
    
    res.json({
      success: true,
      count: recipes.length,
      data: recipes
    });
  } catch (error) {
    console.error('获取菜谱列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取菜谱列表失败',
      error: error.message
    });
  }
};

/**
 * 使用天行API搜索菜谱
 * @route GET /api/diet/recipes/tianapi/search
 * @param {string} query - 搜索关键词
 * @param {number} num - 返回结果数量
 * @param {number} page - 分页参数
 */
exports.searchTianapiRecipes = async (req, res) => {
  try {
    const { query, num = 10, page = 1 } = req.query;
    
    if (!query || !query.trim()) {
      return res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }
    
    console.log(`处理天行API菜谱搜索请求 - 关键词: "${query}", 条数: ${num}, 页码: ${page}`);
    
    // 直接调用天行API获取菜谱信息，不再从本地数据库查询
    const { getRecipeInfo, convertToRecipeModel } = require('../utils/tianapiUtils');
    
    console.log(`开始调用天行API - 关键词: "${query}"`);
    const apiResponse = await getRecipeInfo(query, num, page);
    
    if (apiResponse.success) {
      // 有API结果
      let recipeList = [];
      if (Array.isArray(apiResponse.data) && apiResponse.data.length > 0) {
        // 转换结果格式
        recipeList = apiResponse.data.map(item => {
          const convertedRecipe = convertToRecipeModel(item);
          return convertedRecipe;
        });
        
        console.log(`天行API返回结果: ${recipeList.length} 条`);
        
        return res.json({
          success: true,
          count: recipeList.length,
          data: recipeList
        });
      } else {
        console.log('天行API返回空结果');
        
        return res.json({
          success: false,
          message: '未找到相关菜谱',
          data: []
        });
      }
    } else {
      // API请求失败
      console.error('天行API请求失败:', apiResponse.message);
      
      return res.status(500).json({
        success: false,
        message: apiResponse.message || '搜索菜谱失败',
        data: []
      });
    }
  } catch (error) {
    console.error('搜索菜谱失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索菜谱失败',
      error: error.message
    });
  }
};

/**
 * 保存天行API菜谱到本地数据库
 * @route POST /api/diet/recipes/tianapi/save
 * @param {Object} recipeData - 菜谱数据
 */
exports.saveTianapiRecipe = async (req, res) => {
  try {
    const { recipeData } = req.body;
    const userId = req.user?._id;
    
    if (!recipeData || !recipeData.name) {
      return res.status(400).json({
        success: false,
        message: '菜谱数据不完整'
      });
    }
    
    // 检查菜谱是否已存在
    const existingRecipe = await Recipe.findOne({ name: recipeData.name });
    
    if (existingRecipe) {
      return res.status(400).json({
        success: false,
        message: '该菜谱已存在于数据库中'
      });
    }
    
    // 创建新菜谱
    const recipe = new Recipe({
      ...recipeData,
      source: 'tianapi',
      ...(userId && { createdBy: userId })
    });
    
    await recipe.save();
    
    res.status(201).json({
      success: true,
      message: '成功保存菜谱到数据库',
      data: recipe
    });
  } catch (error) {
    console.error('保存菜谱到数据库失败:', error);
    res.status(500).json({
      success: false,
      message: '保存菜谱到数据库失败',
      error: error.message
    });
  }
};

/**
 * 获取食谱推荐 - 根据关键词和健康状况
 * @route GET /api/diet/recipes/recommend
 * @param {string} condition - 健康状况（如糖尿病）
 * @param {string} keyword - 关键词（如食材名称）
 */
exports.getRecipeRecommendations = async (req, res) => {
  try {
    const { condition, keyword, limit = 4 } = req.query;
    
    // 构建查询条件
    const query = {};
    
    // 如果指定了健康状况
    if (condition) {
      query['suitableFor.condition'] = condition;
    }
    
    // 如果指定了关键词
    if (keyword) {
      // 添加文本搜索
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { 'ingredients.foodName': { $regex: keyword, $options: 'i' } }
      ];
    }
    
    // 先尝试从本地数据库获取
    let recipes = await Recipe.find(query)
      .sort({ featured: -1, updatedAt: -1 })
      .limit(parseInt(limit))
      .select('name description calories carbs protein fat imageUrl cookingTime difficulty');
    
    // 如果本地结果太少且有关键词，尝试通过天行API搜索
    if (recipes.length < parseInt(limit) && keyword) {
      const { getRecipeInfo, convertToRecipeModel } = require('../utils/tianapiUtils');
      const apiResponse = await getRecipeInfo(keyword, parseInt(limit) - recipes.length);
      
      if (apiResponse.success && Array.isArray(apiResponse.data)) {
        // 转换API结果
        const apiRecipes = apiResponse.data.map(item => convertToRecipeModel(item));
        
        // 过滤出符合条件的菜谱
        let filteredApiRecipes = apiRecipes;
        if (condition === '糖尿病') {
          filteredApiRecipes = apiRecipes.filter(r => r.carbs < 50); // 低碳水膳食
        }
        
        // 合并结果
        recipes = [...recipes, ...filteredApiRecipes];
        
        // 保存新获取的菜谱到数据库（异步操作，不等待完成）
        apiRecipes.forEach(async (recipe) => {
          try {
            const existingRecipe = await Recipe.findOne({ name: recipe.name });
            if (!existingRecipe) {
              const newRecipe = new Recipe(recipe);
              await newRecipe.save();
              console.log(`已保存菜谱: ${recipe.name}`);
            }
          } catch (err) {
            console.error(`保存菜谱失败: ${recipe.name}`, err);
          }
        });
      }
    }
    
    // 限制结果数量
    recipes = recipes.slice(0, parseInt(limit));
    
    res.json({
      success: true,
      count: recipes.length,
      data: recipes
    });
  } catch (error) {
    console.error('获取菜谱推荐失败:', error);
    res.status(500).json({
      success: false,
      message: '获取菜谱推荐失败',
      error: error.message
    });
  }
}; 